package com.app.jzgdirector.service.util;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.app.jzgdirector.service.bean.ApkInfo;
import com.common.baselibrary.log.LogUtil;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Eastin on 15/5/27.
 */
public class ApkDownloadService extends Service {
    private final static String TAG = "ApkDownloadService";
    public final static String ACTION_REFRESH = "ApkDownloadRefresh";
    /**
     * 执行下载
     */
    public final static int DOWNLOAD = 0;
    /**
     * 清除Notification
     */
    public final static int CLEAN = 1;
    /**
     * 不要发送请求
     */
    public final static int NO_RECEIVER = 2;

    /**
     * apk包信息
     */
    private ApkInfo apkInfo;
//    private String appName = "";
    private String downUrl = "";
    private String localUrl = "";

    /**
     * -1：下载失败
     * 100：下载完成
     * 0~99：正在下载
     */
    private int iPercent = -1;
    /**
     * 是否发送广播
     */
    private boolean isSendBroadcast = true;

    private ApkDownloadReceiver myReceiver;

    private Handler downloadH = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ApkInfo.REFRESH:
                    if (apkInfo != null) {
                        long loaded = apkInfo.getLoadedSize();
                        long total = apkInfo.getSize();
                        int updateCount = (int) (loaded * 100 / total);
                        if (iPercent != updateCount) {
                            iPercent = updateCount;
                        }
                    }
                    break;
                case ApkInfo.FAIL:
                    break;
                case ApkInfo.OK:
                    Uri uri = Uri.fromFile(new File(localUrl));
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.i(TAG, "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            LogUtil.i(TAG, "onStartCommand");
            //apk名称
            downUrl = intent.getStringExtra("downUrl");
//            appName = intent.getStringExtra("appName");
            download();
        }
        return super.onStartCommand(intent, flags, startId);
    }




    private void download() {
        isSendBroadcast = true;
        if (downUrl != null) {
            new Thread(()-> {
                    long size = 0; //文件大小
                    String fileName = ""; //文件名称
                    //获取文件大小
                    try {
                        URL u = new URL(downUrl);
                        HttpURLConnection urlcon = (HttpURLConnection) u.openConnection();
                        size = urlcon.getContentLength();
                        LogUtil.i(TAG, "SIZE:" + size);
                    } catch (Exception e) {
                        LogUtil.i(TAG, "获取文件大小异常");
                        downloadH.sendEmptyMessage(ApkInfo.FAIL);
                        return;
                    }

                    //获取文件名称
                    String[] urlSplit = downUrl.split("/");
                    if (urlSplit != null) {
                        fileName = urlSplit[urlSplit.length - 1];
                        LogUtil.i(TAG, "fileName:" + fileName);
                    }

                    //初始化ApkInfo
                    apkInfo = new ApkInfo();

                    //获取缓存文件
                    String local = CachePathUtils.getVideoCacheDir();
                    LogUtil.i(TAG, "local:" + local);
                    String apk = local + fileName;
                    File fileApk = new File(apk);

                    localUrl = apk;

                    if (fileApk.exists()) {
                        if (fileApk.length() == size) {
                            apkInfo.setSize(size);
                            apkInfo.setLoadedSize(size);
                            LogUtil.i(TAG, "apk已存在");
                            downloadH.sendEmptyMessage(ApkInfo.OK);
                            return;
                        } else {
                            LogUtil.i(TAG, "apk大小不正确，删除,继续执行！");
                            fileApk.delete();
                        }
                    }

                    if (iPercent == -1 || iPercent == 100) {
                        String suffix = ".tmp";
                        File fileExist = new File(apk + suffix);
                        long loadedSize = 0;
                        if (fileExist.exists()) {
                            LogUtil.i(TAG, "有:" + apk + suffix);
                            loadedSize = fileExist.length();
                        }

                        apkInfo.setDownUrl(downUrl);
                        apkInfo.setLocalPath(local);
                        apkInfo.setApkName(fileName);
                        apkInfo.setSuffix(suffix);
                        apkInfo.setSize(size);
                        apkInfo.setLoadedSize(loadedSize);
                        apkInfo.setEnable(true);

                        DownloadUtil.download2File(ApkDownloadService.this, apkInfo, downloadH);
                        LogUtil.i(TAG, "size:" + apkInfo.getSize() + " loaded:" + apkInfo.getLoadedSize() + " enable:" + apkInfo.isEnable());
                        if (apkInfo.getSize() > 0 && apkInfo.getLoadedSize() == apkInfo.getSize()) {
                            String localPath = apkInfo.getLocalPath() + apkInfo.getApkName();
                            File tmpFile = new File(localPath + apkInfo.getSuffix());
                            tmpFile.renameTo(new File(localPath));
                            downloadH.sendEmptyMessage(ApkInfo.OK);
                            apkInfo.setEnable(false);
                        } else {
                            if (!apkInfo.isEnable()) {
                                downloadH.sendEmptyMessage(ApkInfo.FAIL);
                            } else {
                                downloadH.sendEmptyMessage(ApkInfo.FAIL);
                            }
                        }
                    }
            }).start();
        }

    }

    public class ApkDownloadReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_REFRESH)) {
                int receive_action = intent.getIntExtra("operate", -1);
                LogUtil.i(TAG, "receive_action" + receive_action);
                switch (receive_action) {
                    case CLEAN:
                        LogUtil.i(TAG, "receive_action:clean");
                        if (apkInfo != null) {
                            LogUtil.i(TAG, "receive_action:apkInfo not null");
                            apkInfo.setEnable(false);
                        }
                        cleanReceiver();
                        stopSelf();
                        break;
                    case DOWNLOAD:
                        // 重新下载
                        download();
                        break;
                    case NO_RECEIVER:
                        isSendBroadcast = false;
                        break;
                    default:
                        break;
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        LogUtil.i(TAG, "注销ApkDownloadReceiver");
        cleanReceiver();
        super.onDestroy();
    }

    private void cleanReceiver() {
        try {
            unregisterReceiver(myReceiver);
        } catch (Exception e) {
            LogUtil.i(TAG, e.getMessage());
        }
    }

}
